<template>
    <transition :name="transitionName">
        <div class="body" id="sendPost">
            <div class="new">
                <!--头部-->
                <div class="header">
                    <div class="immersion">
                       <span class="backImg" @click="backRoute()">
                                取消
                            </span>
                        <span class="titlefont"> {{name}}</span>
                        <span class="send" @click="sendPost">发送</span>
                    </div>

                </div>
                <div class="speak">
                    <!--<textarea name="" id="" cols="41" rows="28" v-model="getBody" placeholder="说点什么..." class=" search_input"></textarea>-->
                    <!--el-input 文本框-->
                    <el-input
                            type="textarea"
                            placeholder="说点什么..."
                            resize="none"
                            v-model="getBody" class="search_input">
                    </el-input>
                    <!--el-input-->
                </div>
                <div class="sendImg">
                    <div style="position:relative;">
                        <div class="addImg">
                            <!--<uploader-->
                            <!--url="http://3.112.84.186/api/publics/upload"-->
                            <!--&gt;</uploader>-->
                            <div class="form-cell">
                                <div class="form-horizontal" role="form" id="uploadForm" name="uploadForm"
                                     enctype="multipart/form-data">
                                    <div class="add_phone">
                                        <div class="add_file z_add" v-if="PicIsShow">
                                            <input type="file" name="image[]" id="image[]"
                                                   @change="imageChange('add_phone','add_file')"/>
                                        </div>
                                        <div class="add_file z_addfile" v-for="(item, index) in PicArray"
                                             :key="index">
                                            <img :src="item.imgpath" @click="RemovePhone(index)">
                                        </div>
                                    </div>
                                    <!--遮罩层-->
                                    <div class="z_mask">
                                        <!--弹出框-->
                                        <div class="z_alert">
                                            <p>确定要删除这张图片吗？</p>
                                            <p>
                                                <span class="z_cancel" @click="CancelRemove">取消</span>
                                                <span class="z_sure" @click="SureRemove">确定</span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                        <div class="addBtn" @click="submitImg" v-show="btnShow">
                            确认上传
                        </div>
                    </div>
                    <div class="share">
                        <div class="left" @click="showEmoji = !showEmoji">
                            <img src="@/assets/img/smile.png" alt="">
                        </div>
                    </div>
                    <!--emoji表情-->
                    <transition name="fade">
                        <div class="emoji-box" v-if="showEmoji">
                            <vue-emoji
                                    @select="selectEmoji">
                            </vue-emoji>
                        </div>
                    </transition>
                    <!--emoji-->
                </div>
            </div>
            <Loading v-show="loading"></Loading>
            <Toast :msg="msg" v-if="this.msg!=''" :class="opacity" @toast="square"></Toast>
        </div>
    </transition>
</template>

<script>
    import Toast from '../../components/toast';
    import axios from "axios";
    import sha1 from 'sha1';
    import {site, apiKey} from '../../assets/js/config/site.js';
    import vueEmoji from '../../components/emoji.vue'
    // import {mapState} from 'vuex'
    import Bscroll from 'better-scroll';

    export default {
        name: "sendPost",
        components: {Toast, vueEmoji},
        data() {
            return {
                transitionName: 'slide-left',
                isEmoji: false,
                showEmoji: false,
                data: [],
                imgList: [],
                groupId: "",
                name: "",
                msg: "",
                body: "",
                loading: false,
                imgs: "",
                btnShow: true,
                showAdd: true,
                PicIsShow: true,           //控制 + 号的显示和隐藏
                choosePhone: true,         //必须上传图片
                count: 0,                  //用来判断图片数目
                PicArray: [],              //图片地址数组
                filesArray: [],            //文件数组
            }
        },
        mounted() {
            let that = this;
            mui.init({
                keyEventBind: {
                    backbutton: true  //关闭back按键监听
                }
            });
            // //首页返回键处理
            // //处理逻辑：1秒内，连续两次按返回键，则退出应用；
            var first = null;
            mui.back = function () {
                //首次按键，提示  再按一次退出应用
                if (!first) {
                    first = new Date().getTime();//记录第一次按下回退键的时间
                    that.backRoute()
                    setTimeout(function () {//1s中后清除
                        first = null;
                    }, 1000);
                }
            };

        },
        computed: {
            getBody: {
                get() {
                    return this.body;
                },
                set(v) {
                    this.body = v;
                }
            },
            opacity() {
                return {
                    opacity: this.msg != '',
                }
            },
            // ...mapState({
            //     imgStatus: state => state.imgstore.img_status,
            //     imgPaths: state => state.imgstore.img_paths
            // })
        },
        methods: {
            // 多图上传
            imageChange: function (phone, img) {
                let th = this;
                // 获取点击的文本框
                var file = document.getElementById('image[]')
                // 获取的图片文件
                var fileList = file.files
                // 把文件对象push进数组中, 因为每次都是一张一张传
                this.filesArray.push(fileList[0])
                console.log(this.filesArray)
                // 获得图片名， 大小， 类型(全转换小写)
                var imgName = fileList[0].name
                var imgSize = fileList[0].size
                var imgType = imgName.substring(imgName.lastIndexOf(".") + 1).toLowerCase()
                // 判断是否属于jpg  jpeg png
                if (imgType != 'jpg' && imgType != 'jpeg' && imgType != 'png') {
                    this.$dialog.toast({mes: '只支持jpg , jpeg , png格式', timeout: 1000})
                    imgName = ''
                    fileList = null
                    return false
                }
                // 判断大小
                if (imgSize > 5240000)       // 1M = 1024 * 1024 * 1
                {
                    this.$dialog.toast({mes: '图片不能大于5M', timeout: 1000})
                    fileList = null
                    return false
                }
                else {
                    if (this.count + fileList.length <= 9) {
                        for (let i = 0; i < fileList.length; i++) {
                            // imgUrl是BLOB，常常是数据库中用来存储二进制文件的字段类型
                            var imgUrl = window.URL.createObjectURL(file.files[i])
                            this.PicArray.push({'imgpath': imgUrl})
                        }
                        console.log(this.PicArray)
                        this.count += fileList.length
                        this.choosePhone = false
                        if (this.count == 9) {
                            this.PicIsShow = false
                        }
                    }
                    else {
                        for (let i = 0; i < 9 - this.count; i++) {
                            // imgUrl是BLOB，常常是数据库中用来存储二进制文件的字段类型
                            var imgUrl = window.URL.createObjectURL(file.files[i])
                        }
                        this.count = 9;
                        this.PicIsShow = false;
                    }
                }
                this.picFlag = false   //选中最少一张图片就不显示提示
                file.value = ''   //虽然file的value不能设为有字符的值，但是可以设置为空值
            },
            RemovePhone: function (index) {
                console.log(index)
                this.$store.commit('ChangeRemoveIndex', index)
                // 获得遮布层
                var mask = document.getElementsByClassName("z_mask")[0]
                // 获得取消
                mask.style.display = "block"
            },
            CancelRemove: function () {
                var mask = document.getElementsByClassName("z_mask")[0]
                mask.style.display = "none"
            },
            SureRemove: function () {
                let num = this.$store.state.RemovePicIndex
                var mask = document.getElementsByClassName("z_mask")[0]
                mask.style.display = "none"
                this.PicArray.splice(num, 1)
                this.filesArray.splice(num, 1)
                console.log(this.PicArray)
                if (this.PicArray.length < 9) {
                    this.PicIsShow = true;
                }
            },
            // 上传图片
            submitImg: function () {
                console.log(1);
                let that = this;
                that.loading = true;
                let formData = new FormData()
                this.filesArray.forEach((item, index) => {
                    let imgname = 'imgFiles[' + index + ']'
                    formData.append(imgname, item)
                })
                formData.forEach((v, k) => console.log(k, ' => ', v))
                // 新建请求
                const xhr = new XMLHttpRequest()
                xhr.open('POST', 'http://3.112.84.186/api/publics/upload', true)
                xhr.send(formData)
                xhr.onload = () => {
                    if (xhr.status === 200 || xhr.status === 304) {
                        let datas = JSON.parse(xhr.responseText)
                        console.log('response: ', datas)
                        that.msg = '上传成功';
                        that.loading = false;
                        that.btnShow = false;
                        that.PicIsShow = false;
                        that.imgs = JSON.stringify(datas);
                    } else {
                        alert(`${xhr.status} 请求错误!`)
                    }
                }
            },
            sendPost: function () {
                let uid = localStorage.getItem('uid');
                let that = this;
                let groupId = that.groupId;
                let images = that.imgs;
                if (uid && uid > 0) {
                    if (groupId && groupId > 0) {
                        let body = that.body;
                        if (body == '') {
                            that.msg = "内容不能为空";
                            return false;
                        }
                        let info = {
                            group_id: groupId,
                            user_id: uid,
                            body: body,
                            images: images,
                            accessToken: sha1(groupId + uid + body + images + apiKey)
                        }
                        console.log(info)
                        let url = site + '/api/group_posts/createPost';
                        axios.post(url, info).then(function (response) {
                            if (response.data.status == 1 && response.data.code == 0) {
                                that.msg = "发布成功";
                                setTimeout(function () {
                                    that.changeRoute('/classIndex', {groupId: groupId, from: 'sendPost'});
                                }, 1000);
                            } else {
                                that.msg = "发布失败";
                                return false;
                            }
                        }).catch(function (error) {
                            console.log(error);
                            that.msg = "发布错误";
                            return false;
                        });
                    } else {
                        that.msg = "请选择班级";
                        setTimeout(function () {
                            that.changeRoute('/myJoin');
                        }, 1000);
                    }
                } else {
                    that.msg = "请重新登录";
                    setTimeout(function () {
                        that.changeRoute('/');
                    }, 1000);
                }
            },
            square(v) {
                this.msg = v
            },
            selectEmoji(code) {
                this.getBody += code
            },
            submit() {
                this.data.push(this.getBody)
                this.getBody = ''
            },
        }
        ,
        created() {
            this.groupId = this.$route.query.groupId;
            this.name = this.$route.query.name;
            if (this.$route.query.from == 'classIndex') {
                this.transitionName = 'slide-right';
            }
            this.replaceRoute('/sendPost')
        }
        ,
        watch: {
            // imgStatus() {
            //     if (this.imgStatus === 'finished') {
            //         this.submits()
            //     }
            // }
        }
        ,
        destoryed() {
            this.imgs = []
        }
    }
</script>

<style lang="scss">
    @import "../../assets/css/class/sendPost.scss";

    ul {
        margin: 0;
        padding: 0;
        list-style: none;
    }

    .clearfix {
        &:after {
            content: '';
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
    }

    .fade-enter-active, .fade-leave-active {
        transition: all 0.4s;
    }

    .fade-enter, .fade-leave-to {
        transform: translateY(10rem);
    }

    .fade-enter-to, .fade-leave {
        transform: translateY(0rem);
    }

    .bg-enter-active, .bg-leave-active {
        transition: all 0.8s;
    }

    .bg-enter, .bg-leave-to {
        opacity: 0;
    }

    .btn {
        width: 100%;
        height: 3em;
        background-color: green;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .file-uploads {
        margin-left: 5px;
        display: inline-block;
        width: 1.8rem;
        height: 2rem;
        line-height: 2rem;
        font-size: .4rem;
        font-weight: normal;
        border: 1px dashed #000;
        border-radius: 4px;
        position: relative;
    }

    input[type='file'] {
        opacity: 0;
        z-index: -1;
    }

    .upload-add {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }

    /*图片的大小*/
    .add_phone img {
        display: block;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    /*每张图片都是一个div*/
    .z_addImg {
        float: left;
        margin-left: 0.1rem;
        margin-bottom: 0.1rem;
    }

    /*+ 号的样式*/
    .add_file {
        display: inline-block;
        width: 1.8rem;
        height: 2rem;
        margin-left: 5px;
        position: relative;
        z-index: 10;
        flex: 0 0 1.8rem;
    }

    .z_add {
        background: url('../../assets/img/downn.png') no-repeat;
        background-size: 100% 100%;
    }

    .imgClass {
        width: 1.8rem;
        height: 2rem;
        background-size: 100% 100%;
        float: left;
        margin-right: 10px;
        margin-bottom: 10px;
    }

    .add_file input::-webkit-file-upload-button {
        width: 5.5rem;
        height: 5.5rem;
        border: none;
        position: absolute;
        outline: 0;
        opacity: 0;
    }

    .add_file input[name='image[]'] {
        float: left;
        width: auto;
        border: 0;
        vertical-align: middle;
    }

    /*遮罩层*/
    .z_mask {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, .5);
        position: fixed;
        top: 0;
        left: 0;
        z-index: 999;
        display: none;
    }

    /*弹出框*/
    .z_alert {
        width: 56%;
        border-radius: .2rem;
        background: #fff;
        font-size: 14px;
        text-align: center;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }

    .z_alert p:nth-child(1) {
        padding: .4rem 0rem;
        font-size: 14px;
    }

    /*取消和确定*/
    .z_alert p:nth-child(2) span {
        display: inline-block;
        width: 49%;
        height: .8rem;
        line-height: .8rem;
        float: left;
        border-top: 1px solid #ddd;
    }

    /*给取消和确定添加边框*/
    .z_cancel {
        border-right: 1px solid #ddd;
    }
</style>